package grammar.parser.stmt;

import error.processing.MyErrorProcessing;
import word.parser.WordElement;

public class BreakContinueStmt extends Stmt {
    private final boolean isBreak;
    private WhileStmt whileStmt;

    public BreakContinueStmt(boolean isBreak) {
        this.isBreak = isBreak;
    }

    public static BreakContinueStmt buildBreakContinueStmt() {
        assert getAnalyzingWord().getType() == WordElement.WordType.BREAKTK ||
                getAnalyzingWord().getType() == WordElement.WordType.CONTINUETK;
        boolean isBreak = getAnalyzingWord().getType() == WordElement.WordType.BREAKTK;
        if (getSemanticParser().getCycleLayerNum() == 0) {
            MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.m,
                    getAnalyzingWord());
        }
        analyzeNextWord();

        if (getAnalyzingWord().getType() != WordElement.WordType.SEMICN) {
            MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.i, getAnalyzingWord(-1));
        } else {
            analyzeNextWord();
        }
        return new BreakContinueStmt(isBreak);
    }

    @Override
    public void execute() {
        whileStmt = getSemanticParser().getLastCycle();
        getSemanticParser().callBreakOrContinue();
        if (isBreak) {
            whileStmt.callBreak();
        } else {
            whileStmt.callContinue();
        }
    }
}
